package com.tg.base.concurrent.synch;

import com.google.common.collect.Lists;
import com.tg.base.concurrent.SlowAction;
import org.apache.commons.collections4.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class SynchronizedTest {

    private static final Map<String, String> MAP = new HashMap<>();

    private static final ExecutorService executorTomcat = Executors.newFixedThreadPool(2);
    private static final ExecutorService executorAsync = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        executorTomcat.submit(invokeRequest());
        executorTomcat.submit(invokeRequest());

    }

    private static Runnable invokeRequest() {
        return () -> {
            String key = "中台客群";
            if (MAP.containsKey(key)) {
                System.out.println(MAP.get(key));
            } else {
                FutureTask<String> syncData = new FutureTask<>(() -> {
                    System.out.println(Thread.currentThread().getName() + ":working");
                    SlowAction.invoke();
                    System.out.println(Thread.currentThread().getName() + ":done");

                    return "jsonData";
                });
                executorAsync.submit(syncData);

                String value = "";
                try {
                    value = syncData.get(10, TimeUnit.SECONDS);
                } catch (InterruptedException | ExecutionException | TimeoutException ex) {
                    ex.printStackTrace();
                }
                MAP.put(key, value);
            }
        };
    }
}
